package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysService;
import com.ktjiaoyu.service.impl.SysServiceImpl;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/main")
public class SysController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysServiceImpl.class);
    @Autowired
    SysService sysService;

    @ResponseBody
    @GetMapping("/oldPasswordCheck")
    public Map<String, Object> oldPasswordCheck(String oldPassword) throws Exception {

        SysUser sysUser = (SysUser) session(Constants.SESSION_USER);
        Map<String, Object> result = new HashMap<>();
        if (oldPassword == "" || oldPassword == null) {
            result.put("error", "输入不能为空,请重新输入");
        } else {
            try {
                boolean ok = sysService.verifyOldPassword(sysUser.getId().intValue(), oldPassword);
                if (ok) {
                    result.put("pass", 1);
                } else {
                    result.put("pass", 0);
                }
            } catch (Exception e) {
                LOGGER.error("执行SysController.oldPasswordCheck(oldPassword)方法出现异常", e);
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    @GetMapping("/changePwd")
    public String changePwd() {
        return "sys/changePwd";
    }

    //个人密码修改
    @PostMapping("/FchangePwd")
    public String FchangePwd(String password) throws Exception {
        SysUser sysUser = (SysUser) session(Constants.SESSION_USER);
        sysUser.setPassword(password);
        sysUser.setId(sysUser.getId());
        sysUser.setUpdatedTime(new Date());
        sysUser.setUpdatedUserId(sysUser.getId());
        boolean ok = sysService.changePassword(sysUser);
        if (ok) {
            return redirect("/login.jsp");
        } else {
            return redirect("/main/changePwd");
        }
    }


}
